<template>
  <el-row class="section">
    <el-col :span="6" class="organization-padd">
      <el-col :span="24">
        <el-tree
          style="
            margintop: 10px;
            min-height: calc(100vh - 120px);
            border-radius: 10px;
          "
          :data="content"
          :props="defaultProps"
          @node-click="handleClick"
          node-key="id"
          :default-expanded-keys="[2]"
          :expand-on-click-node="false"
        >
          <div class="node" slot-scope="{ node, data }">
            <div>{{ node.label }}</div>

            <el-select
              v-if="nodeCurr.id == data.id"
              v-model="treeValue"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </el-tree>
      </el-col>
    </el-col>
    <el-col :span="18">
      <el-form :inline="true" :model="formSelect" class="formSection-flex">
        <el-form-item label="模板名称">
          <el-input v-model="formSelect.name" placeholder="模板名称"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-select
            v-model="formSelect.statusValue"
            placeholder="请选择启用/禁用"
          >
            <el-option
              v-for="item in statusSeclet"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handelSeach">查询</el-button>
          <el-button
            type="primary"
            @click="tplIndex() "
            >重置</el-button
          >
          <el-button type="primary" @click="addHtml(1)">新增旧版本</el-button>
           <el-button type="primary" @click="addHtml(2)">新增新版本</el-button>
       
        </el-form-item>
          <el-form-item label="新版本">
    
         <span style=" display: inline-block;
  width: 30px;
  height: 30px;
  background:#65da8a;"></span>
     
             </el-form-item>
      </el-form>
    
      <el-col :span="24" class="formList">
        <!-- <FromList :tableTitle="tableTitle" @handleEdit="handleEdit"  :tableData="tableData"   /> -->
        <el-table v-loading="params.loading"
         :row-class-name="tableRowClassName"
         :data="tableData" border>
          <el-table-column type="index" width="70" label="序号">
          </el-table-column>
          <template v-for="(item, index) in tableTitle">
            <el-table-column
              :width="item.width"
              v-if="item.prop == 'use_role'"
              :prop="item.prop"
              :label="item.name"
              :key="index"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.use_role">
                  <span v-for="(item, index) in use_roles" :key="index">
                    <span v-if="item.value == scope.row.use_role">{{
                      item.label
                    }}</span>
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :width="item.width"
              v-else-if="item.prop == 'use_dept'"
              :prop="item.prop"
              :label="item.name"
              :key="index"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.use_dept">
                  {{ scope.row.use_dept.name }}
                </div>
              </template>
            </el-table-column>
             <el-table-column
              :width="item.width"
              v-else-if="item.prop == 'create_by_info'"
              :prop="item.prop"
              :label="item.name"
              :key="index"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.create_by_info">
                  {{ scope.row.create_by_info.real_name }}
                </div>
              </template>
            </el-table-column>
                <el-table-column
              :width="item.width"
              v-else-if="item.prop == 'status'"
              :prop="item.prop"
              :label="item.name"
              :key="index"
            >
              <template slot-scope="scope">
                <!-- <div v-if="scope.row.create_by_info">
                  {{ scope.row.create_by_info.real_name }}
                </div> -->
                <el-switch
  v-model="scope.row.status==1"
  active-color="#13ce66"
  inactive-color="#ff4949"
  @change="setsetatus(scope.row)"
  >
</el-switch>

                
              </template>
            </el-table-column>
            <el-table-column
              v-else
              :width="item.width"
              :prop="item.prop"
              :label="item.name"
              :key="index + item"
            >
            </el-table-column>
          </template>
          <el-table-column label="更多" width="300" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleEdit({key:1, data:scope.row})"
                >修改文件</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleEdit({key:2, data:scope.row})"
                >修改模板</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleEdit({key:3, data:scope.row})"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
         <div>
           <el-pagination
           class="fenye"
            :background="true"
            :current-page="paramsList.page"
            :page-size="paramsList.limit"

            layout="prev, pager, next"
            @current-change="handlePagination"
            :total="paramsList.pageCount">
            </el-pagination>
      </div>
      </el-col>
    </el-col>
    <el-dialog
      :title="type == 1 ? '新增' : type == 2 ? '编辑' : ''"
      :visible.sync="addVisible"
      width="50%"
      :before-close="handleClose"

    >
      <span>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="分类名称">
            <el-input
              v-model="formInline.name"
              placeholder="分类名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="上级分类" v-if="type == 1">
            <el-input v-model="nodeCurr.name" disabled></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClick()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-if="typeFlag"
      :title="typeForm == 1 ? '新增' : typeForm == 2 ? '编辑' : ''"
      :visible.sync="typeFlag"

      :before-close="handleClose"
        :close-on-click-modal="false"

          :modal-append-to-body="false"
           :destroy-on-close="true"

    >
      <span>
        <el-form :inline="true" :model="formHtml" class="demo-form-inline">
          <el-form-item label="模板名称">
            <el-input
              size="mini"
              v-model="params.name"
              placeholder="模板名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="模板分类" v-if="type == 1">
            <!-- <el-input  size="mini" v-model="nodeCurr.name" disabled></el-input> -->
            <el-cascader
              size="mini"
              v-model="params.category_id"
              :options="content"
              :props="template.props"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="使用科室">
            <el-cascader
              size="mini"
              @change="changeSubject"
              v-model="params.use_dept"
              :options="vuex_subject.data"
              :props="subject.props"
              clearable
            ></el-cascader>
          </el-form-item>

          <el-form-item label="模板角色">
            <el-select
              size="mini"
              v-model="params.use_role"
              placeholder="模板角色"
            >
              <el-option
                v-for="(item, index) in use_roles"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </span>
      <div>
        <div style="font-weight: bold; padding-bottom: 13px">模板内容：</div>
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="请输入模板内容"
          v-model="params.content"
        >
        </el-input>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="typeFlag = false">取 消</el-button>
        <el-button type="primary" @click="nativeHtml">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="查看"
      :visible.sync="iframeFlag"
      :fullscreen="true"
      :close-on-click-modal='false'
      :before-close="
        () => {
          iframeFlag = false;
        }
      "
    >
      <span>
        <iframeDemo :url="overUrl" ref="iframeDemo" height="500px" />
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="iframeFlag = false">取 消</el-button>
        <el-button type="primary" @click="iframeFlag = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改文件"
     :visible.sync="iframeFlag2"
     :fullscreen="true"
     :close-on-click-modal='false'
     :before-close="handleIframe"
    >
      <span>
        <!-- <iframeDemo :url="overUrl2" ref="iframeDemo2" height="500px" /> -->
        <iframeDemo2 :url="overUrl2" :dataurl='dataurl' ref="iframeDemo2" height="500px" />
        <!-- <compile :url='overUrl2' :dataurl='dataurl'/> -->
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleIframe">取 消</el-button>
        <el-button type="primary" @click="handleIframe">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
import { categoryIndex, categorySave, tplIndex,tplSaveV2,deleteTpl,saveTpl} from "@/api/caseList";
import iframeDemo from "@/components/iframeDemo/index.vue";
import iframeDemo2 from "@/components/iframeDemo2/index.vue";
import FromList from "@/forComponents/fromList/fromList";
import compile from '../compile/index.vue'
import { iframeUrl,http2 } from "@/utils/server.js";
import { mapState, mapActions } from "vuex";
let that;
export default {
  name:"caseList",
  data() {
    return {
      paramsList:{
        page:1,
        limit:10,
        pageCount:0,
      },
      subject: {
        props: {
          value: "id",
          label: "name",
          children: "children",
          checkStrictly: true,
        },
      },
      template: {
        props: {
          value: "id",
          label: "name",
          children: "children",
          checkStrictly: true,
        },
      },
      params: {
        name: "",
        content: "",
        category_id: "",
        use_dept: {
          id: "",
          name: "",
        },
        use_dept1: {
          id: "",
          name: "",
        },
        use_role: "",
        id: "",
      },
      use_roles: [
        {
          label: "通用",
          value: 1,
        },
        {
          label: "医生",
          value: 2,
        },
        {
          label: "护士",
          value: 3,
        },
      ],
    dataurl:{},
      tableTitle: [
        {
          prop: "name",
          name: "模板病例名称",
          type: 1,
          width: 200,
        },
        {
          prop: "use_role",
          name: "模板类型",
          type: 1,
          width: 100,
        },
        {
          prop: "use_dept",
          name: "使用科室",
          type: 1,
        },
        {
          prop: "updated_at",
          name: "更新时间",
          type: 1,
          width: 200,
        },
        {
          prop: "create_by_info",
          name: "更新人",
          type: 1,
        },
         {
          prop:"status",
          name:"启用状态",
          type:5,
        },
      ],
      tableData: [],
      data: [],
      content: [],
      height: "0",
      url: `http://localhost:8080/#/caseList?id=1&token=${localStorage.getItem(
        "token"
      )}`,
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: "isLeaf",
      },
      nodeCurr: {},
      treeValue: "",
      options: [
        {
          label: "新增下级",
          value: "1",
        },
        {
          label: "编辑",
          value: "2",
        },
      ],
      addVisible: false,
      type: 1,
      formInline: {
        name: "",
      },
      formSelect: {
        name: "",
        statusValue: "",
      },
      statusSeclet: [
         {
          label: "全部",
          value: '',
        },
        {
          label: "启用",
          value: 1,
        },
        {
          label: "禁用",
          value: 2,
        },
      ],
      typeFlag: false,
      typeForm: 1,
      formHtml: {
        name: "",
        use_dept: "",
        id: "",
      },
      iframeFlag: false,
      iframeFlag2:false,
      overUrl: "",
      overUrl2: "",
      olandnew:1,
    };
  },
  watch: {
    treeValue(to) {
      if (to == 1) {
        this.addVisible = true;
        this.type = 1;
      } else if (to == 2) {
        this.addVisible = true;
        this.type = 2;
        this.formInline.name = this.nodeCurr.name;
      }
    },
  },
  computed: {
    ...mapState({
      vuex_subject: (state) => state.dictBai.vuex_subject,
    }),
  },
  mounted() {
    that = this;
    // this.height = (document.body.offsetHeight - 200) + "px"
    this.categoryIndex();

  },
  methods: {
      tableRowClassName({ row, rowIndex }) {
      if (row.is_new === 1) {
        return "is_new-1";
      } else if (row.is_new === 2) {
        return "is_new-2";
      } 
    },
    handleIframe(){
      this.iframeFlag2 = false
      // that.$refs.iframeDemo2.handleUrl();
    },
    ...mapActions(["dictBai/getDeptIndex"]),
    handlePagination(e){

         this.paramsList.page=e;

            this.tplIndex()


    },
    changeSubject(item) {
      if (item.length > 0) {
        this.vuex_subject.data.forEach((v1) => {
          if (v1.id == item[0]) {
            if (item.length > 1) {
              v1.children.forEach((v2) => {
                if (v2.id == item[1]) {
                  if (item.length > 2) {
                    v2.children.forEach((v3) => {
                      if (v3.id == item[2]) {
                        if (item.length > 3) {
                          v3.children.forEach((v4) => {
                            if (v4.id == item[4]) {
                              this.params.use_dept1.id = v4.id;
                              this.params.use_dept1.name = v4.name;
                            }
                          });
                        } else {
                          this.params.use_dept1.id = v3.id;
                          this.params.use_dept1.name = v3.name;
                        }
                      }
                    });
                  } else {
                    this.params.use_dept1.id = v2.id;
                    this.params.use_dept1.name = v2.name;
                  }
                }
              });
            } else {
              this.params.use_dept1.id = v1.id;
              this.params.use_dept1.name = v1.name;
            }
          }
        });
        console.log("this.params.use_dept1", this.params.use_dept1);
      }
    },

    // 操作按钮点击
    handleEdit(e) {
      // console.log(e)
      switch (e.key) {
        case 1:
          this.typeForm = 2;
          // let data = {
          //   name: e.data.name,
          //   category_id: this.nodeCurr.id,
          //   type: this.typeForm,
          // };
          // if (data.type == 2) {
          //   data.id = e.data.id;
          // }
          // data = JSON.stringify(data);
          // localStorage.setItem("formHtml", data);
          // this.$router.push({path:"/admin/compile",query:{id:e.data.id,name:e.data.name,category_id:this.nodeCurr.id}});
        if(e.data.is_new==1){
                this.iframeFlag2 = true;
         this.overUrl2= `${iframeUrl}/#/alter?id=${e.data.id}&name=${e.data.name}&token=${localStorage.getItem("token")}&category_id=${this.nodeCurr.id}`
        setTimeout(function () {
          that.$nextTick(function () {
            let json = {
              id:e.data.id,
              name:e.data.name,
              token:localStorage.getItem("token"),
              category_id:that.nodeCurr.id,
            };
            that.$refs.iframeDemo2.handleEmit(json);
          });
        }, 200);
        }else{
          // var http=process.env.VUE_APP_BASE_API+''
          var http=http2+'?tepid='+e.data.id+'&is_pattern=1&uid=""&source=2'
        // var http=`${http2}?tepid=${item.tpl_id}&is_pattern=2&uid=${this.id}&source=1&his_uid=${this.real_id}&real_name=${this.real_name}&tep_name=${item.tpl_name}&cid=${item.id}`
          
          window.open(http,'_blank');
        }
      
        break;

        case 2:
            this.params.use_dept=[];
            this.params.category_id =[];
          console.log('e.data',e.data)
          this["dictBai/getDeptIndex"]().then((res) => {
            this.typeForm = 2;
            this.params.name = e.data.name;
            this.params.id = e.data.id;
           let category_id= e.data.categoryArry
              ? e.data.categoryArry.split(",")
              : [e.data.category_id];


           category_id.forEach(v=>{
              this.params.category_id.push(parseInt(v))
           })

          console.log(" this.params.category_id", this.params.category_id)
           if(e.data.use_dept){
              let use_dept=e.data.use_deptArry
              ? e.data.use_deptArry.split(",")
              : [e.data.use_dept.id];

              use_dept.forEach(v=>{
                this.params.use_dept.push(parseInt(v))
              })

            this.params.use_dept1.id = e.data.use_dept.id;
            this.params.use_dept1.name = e.data.use_dept.name;

             console.log("进啦了吗", this.params.use_dept)

           }

            this.params.use_role = e.data.use_role;
            this.typeFlag = true;
          });

          break;
        case 3:
                    this.$confirm("是否删除", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
          }).then(() => {
                deleteTpl({id: e.data.id,}).then(res=>{
                       if (res.code == 200) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                });
                this.tplIndex();
              } else {
                this.$message(res.message);
              }
          })
       
          });

          break;
      }
    },
    setsetatus(row){
     var  d={
          id:row.id,
          status:row.status==1?2:1
      }
        saveTpl(d).then(res=>{
              if(res.code==200){
                 this.$message({
            message: '成功',
            type: "success",
          });
              }
          this.tplIndex();

        })
    },
    // 跳转新增
    nativeHtml() {
      console.log(this.params);

      if (!this.params.name) {
        this.$message.error("请输入模板名称");
        return false;
      }
      let d = {
        name: this.params.name,
        content: this.params.content,
        category_id:
          this.params.category_id[this.params.category_id.length - 1],
        use_dept: this.params.use_dept1,
        use_role: this.params.use_role,
        categoryArry: this.params.category_id.toString(),
        use_deptArry: this.params.use_dept.toString(),
      };

      if (this.typeForm == 2) {
        d.id = this.params.id;
        delete d.content
      }

    if(this.olandnew==1){
         this["_API"].getmedical_record_tplTplSave(d).then((res) => {
        console.log("res", res);
        if (res.code == 200) {
          this.$message({
            message: res.message,
            type: "success",
          });
          this.typeFlag = false;
          this.tplIndex();
        }
      });
    }else{
      tplSaveV2(d).then((res) => {
        console.log("res", res);
        if (res.code == 200) {
          this.$message({
            message: res.message,
            type: "success",
          });
          this.typeFlag = false;
          this.tplIndex();
        }
      });
    }
     
      // if(data.type == 2){
      //    data.id = this.formHtml.id
      // }
      // data = JSON.stringify(data)
      // localStorage.setItem("formHtml",data)
      // this.$router.push("/admin/compile")
    },
    // 添加编辑模板分类
    addClick() {
      let data = {
        name: this.formInline.name,
      };
      if (this.type == 1) {
        data.pid = this.nodeCurr.id;
      } else {
        data.id = this.nodeCurr.id;
      }
      categorySave({ ...data })
        .then((res) => {
          this.addVisible = false;
          this.$set(this.formInline, "name", "");
          this.$message({
            message:
              this.type == 1 ? "添加成功" : this.type == 2 ? "编辑成功" : "",
            type: "success",
          });
          this.categoryIndex();
        })
        .catch((e) => {
          this.$message({
            message: e.message,
            type: "error",
          });
        });
    },
    tplIndex() {
      tplIndex({page:this.paramsList.page,limit:this.paramsList.limit, category_id: this.nodeCurr.id, keyword: this.formSelect.name,status:this.formSelect.statusValue })
        .then((res) => {
          console.log(res);
          if (res.data.list.length == 0) {
            return false;
          }
          this.tableData = res.data.list;
          this.paramsList.pageCount=res.data.count;
        })
        .catch((e) => {
          this.$message({
            message: e.message,
            type: "error",
          });
        });
    },
    addHtml(index) {
      this["dictBai/getDeptIndex"]().then((res) => {
        this.params = {
          name: "",
          content: "",
          category_id: "",
          use_dept: [],
          use_dept1: {
            id: "",
            name: "",
          },
          use_role: "",
          id: "",
        };

        this.typeFlag = true;
        this.olandnew=index
        this.typeForm = 1;
      });
    },
    handleClose() {
      this.addVisible = false;
      this.typeFlag = false;
      this.$set(this.formInline, "name", "");
      this.treeValue = "";
    },
    clickUrl() {
      this.url = `http://localhost:8080/#/caseList?id=2&token=${localStorage.getItem(
        "token"
      )}`;
    },
    // 左边组织机构点击
    handleClick(e) {
      this.nodeCurr = e;
      this.paramsList.page=1;
      this.tplIndex();
      this.tableData = [];
      this.treeValue = "";
    },
    // 获取左边组织框架
    categoryIndex() {
      categoryIndex({ status: 1, user_for: 1 ,page:1,limit:20,})
        .then((res) => {
          console.log(res);
          if (res.data.length == 0) {
            return false;
          }
          this.content = res.data;
          this.nodeCurr = res.data[0];
          this.paramsList.page=1;
          this.tplIndex();
        })
        .catch((e) => {
          this.$message({
            message: e.message,
            type: "error",
          });
        });
    },
    // 点击查询
    handelSeach() {
      this.tableData = [];
      this.tplIndex();
    },
    handleNodeClick(id) {},
  },
  components: {
    iframeDemo,
    FromList,
    // compile,
    iframeDemo2
  },
};
</script>
<style >
.el-table .is_new-1 {

      background: #DCDFE6 !important;
}

.el-table .is_new-2 {
      background: #65da8a !important;
}
</style>
<style lang="scss" scoped>
@import "./index.scss";

.organization-padd {
  padding: 0 20px;
  box-sizing: border-box;
  border-radius: 10px;
  min-height: calc(100vh - 90px);
}

.buttom {
  text-align: right;
  margin-top: 20px;
  margin-bottom: 20px;
}

.pd-20 {
  padding: 0px 20px;
  box-sizing: border-box;
}
>>> .el-tree-node__content {
  &:hover {
    // background: #89c2f7;
    // background: red;
  }
  height: 40px;
  display: flex !important;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.node >>> .el-select .el-input__inner {
  height: 30px;
}
.node >>> .el-select {
  width: 100px;
  line-height: 30px;
  height: 30px;
  // margin-left: 50px;
  margin-left: auto;
}

.custom-tree-title {
  display: inline-block;
  height: 30px;
}

>>> .el-input__icon {
  line-height: 30px;
}
.section-content {
  height: calc(100vh - 90px);
  display: flex;
}

.node {
  width: 90%;
  display: flex;
  line-height: 30px;
}

.flexBetween {
  display: flex;
  justify-content: space-between;
 
}

.scrool {
  overflow-y: scroll;
  height: 500px;
  display: block;
}

  .fenye{
    text-align: right;
    margin-top: 20px;
  }
</style>
